import type {
  HttpProvider,
  IReqJsonRpc,
} from "@monorepo/shared/hooks/http/types";

const BaseUrl = "http://localhost:9527/api/rpc/v1/";

export const fetchPrivoder: HttpProvider = (
  params: IReqJsonRpc,
  onDone?: <T>(Data: T) => void,
  onBusError?: (error: any) => void,
  onSvcError?: (error: any) => void
) => {
  fetch(`${BaseUrl}`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      // authorization: "Bearer " + localStorage.getItem("token"),
    },
    mode: "cors",
    body: JSON.stringify(params),
  })
    .then((response) => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error("Network response was not ok");
      }
    })
    .then((data) => {
      // console.log("data", data);

      if (data.code === 200) {
        if (onDone) onDone(data);
      } else {
        if (onBusError) {
          onBusError(data.msg);
        }
      }
    })
    .catch((error) => {
      if (onSvcError) {
        onSvcError(error);
      }
    });
};
